package com.lyf.juc.practice.cas;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author LYF
 * @date 2022/7/12
 */
public class AtomicStampedRefTests {
    private final static class User{
        int age;String name;

        public User(int age, String name) {
            this.age = age;
            this.name = name;
        }

        @Override
        public String toString() {
            return "User{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    // 不仅需要保证内容一致，还需要中间过程无改动
    public static void main(String[] args) {
        User user1 = new User(1,"hello1");
        User user2 = new User(2,"hello2");
        AtomicStampedReference<User> atomicStampedReference = new AtomicStampedReference<>(user1,1);
        System.out.println(atomicStampedReference.getStamp()+"::"+atomicStampedReference.getReference());
        atomicStampedReference.compareAndSet(user1,user2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp()+1);
        System.out.println(atomicStampedReference.getStamp()+"::"+atomicStampedReference.getReference());
        atomicStampedReference.compareAndSet(user2,user1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp()+1);
        System.out.println(atomicStampedReference.getStamp()+"::"+atomicStampedReference.getReference());
    }
}
